package juc.popular.aqs;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * CountDownLatch计数器
 * <p>
 * * {@link CountDownLatch#CountDownLatch(int)}   指定计数的次数，只能被设置1次
 * * {@link CountDownLatch#countDown()}           调用此方法则计数减1
 * * {@link CountDownLatch#await()}               调用此方法会一直阻塞当前线程，直到计时器的值为0，除非线程被中断
 * * {@link CountDownLatch#await(long, TimeUnit)} 调用此方法会一直阻塞当前线程，直到计时器的值为0，除非线程被中断或者计数器超时，返回false代表计数器超时。
 * * {@link CountDownLatch#getCount()}            获取计数器数量
 *
 * @author 王霄
 * @date 2020/9/10
 */
public class CountDownLatchDemo {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(3);

        System.out.println("老板正在等所有的工人工作完成......");

        new Worker("工人A",countDownLatch).start();
        new Worker("工人B",countDownLatch).start();
        new Worker("工人C",countDownLatch).start();
        countDownLatch.await();

        System.out.println("老板开始检查工作");
    }

    public static class Worker extends Thread {
        private final CountDownLatch countDownLatch;

        public Worker(String name, CountDownLatch countDownLatch) {
            super(name);
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            System.out.printf("%s工作中%n" , getName());
            try {
                TimeUnit.SECONDS.sleep(new Random().nextInt(10));
            } catch (InterruptedException ignored) {
            }
            System.out.printf("%s工作结束%n" , getName());
            countDownLatch.countDown();
        }
    }
}